import { RbacMenuType } from '@/data/auth/menu';
import { MenuTypeEnum } from '@/enums/auth';
import { IconOutlinedValueEnum } from '@/enums/icon';
import { useMenus } from '@/hooks/auth/useMenus';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { ProFormGroup } from '@ant-design/pro-form/lib';
import React, { useEffect, useRef, useState } from 'react';

const AddModal: React.FC<{
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: RbacMenuType) => Promise<void>;
  values?: Partial<RbacMenuType>;
}> = ({ visible, onCancel, onSubmit, values }) => {
  const [menuType, setMenuType] = useState<any>();
  const { allMenuValueEnum } = useMenus();
  const formRef = useRef<any>(null);

  useEffect(() => {
    if (formRef.current && visible) {
      formRef.current.resetFields();
    }
  }, [values, visible]);
  const getModalFormKey = () => {
    if (values && values.id) {
      return values?.id || Math.random();
    } else {
      return Math.random();
    }
  };

  return (
    <ModalForm
      title="新建"
      width="800px"
      open={visible}
      onFinish={onSubmit}
      formRef={formRef}
      onOpenChange={(value) => {
        if (!value) onCancel();
      }}
      key={`menu-add-form-${getModalFormKey()}`}
    >
      <ProFormGroup colProps={{ span: 12 }}>
        <ProFormSelect
          width="md"
          name="parentId"
          label={'父级ID'}
          placeholder={'请输入父级ID'}
          valueEnum={allMenuValueEnum}
          onChange={(value) => {
            if (value) {
              setMenuType(MenuTypeEnum.Leaf);
            } else {
              setMenuType(MenuTypeEnum.Root);
            }
          }}
          initialValue={values?.id || ''}
        />
        {menuType === MenuTypeEnum.Root && (
          <ProFormSelect
            rules={[
              {
                required: true,
                message: '图标为必填项',
              },
              (form) => ({
                validator: (_, value) => {
                  const menuType = form.getFieldValue('menuType');

                  if (menuType === MenuTypeEnum.Root) {
                    if (!value) return Promise.reject('根菜单必须选图标');
                  }
                  if (menuType === MenuTypeEnum.Leaf) {
                    if (value) return Promise.reject('叶子菜单不用选图标');
                  }
                  return Promise.resolve();
                },
              }),
            ]}
            width="md"
            name="icon"
            label="图标"
            placeholder="请选择图标"
            valueEnum={IconOutlinedValueEnum}
          />
        )}
      </ProFormGroup>

      <ProFormGroup colProps={{ span: 12 }}>
        <ProFormText
          rules={[
            {
              required: true,
              message: '菜单名称为必填项',
            },
            {
              pattern: /^[a-zA-Z0-9]+$/,
              message: '只能输入英文字符',
            },
          ]}
          width="md"
          name="name"
          label={'菜单名称'}
          placeholder={'请输入菜单名称'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '菜单中文名称为必填项',
            },
            {
              pattern: /^[\u4e00-\u9fa50-9]+$/,
              message: '只能输入中文字符',
            },
          ]}
          width="md"
          name="cnName"
          label={'菜单中文名称'}
          placeholder={'请输入菜单中文名称'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '路由路径为必填项',
            },
            () => ({
              validator: (_, value) => {
                if (menuType === MenuTypeEnum.Root) {
                  if (!value.startsWith('/')) {
                    return Promise.reject('根菜单路径必须以/开头');
                  }
                }
                if (menuType === MenuTypeEnum.Leaf) {
                  if (value.startsWith('/')) {
                    return Promise.reject('叶子菜单路径不能以/开头');
                  }
                }
                if (!/^[a-zA-Z0-9/-]*$/.test(value)) {
                  return Promise.reject('只能包含英文字母、数字、斜杠和短横线');
                }
                return Promise.resolve();
              },
            }),
          ]}
          width="md"
          name="path"
          label={'路由路径'}
          placeholder={'请输入路由路径'}
        />

        <ProFormText
          rules={[
            {
              required: true,
              message: '排序为必填项',
            },
            {
              pattern: /^\d+$/,
              message: '请输入数字',
            },
          ]}
          width="md"
          name="sort"
          label={'排序'}
          placeholder={'请输入排序号'}
        />
      </ProFormGroup>
    </ModalForm>
  );
};

export default AddModal;
